<template>
  <div class="region-select">
    <el-form-item label="省份" prop="province" required>
      <el-select
        v-model="provinceValue"
        placeholder="请选择省份"
        style="width: 100%"
        @change="handleProvinceChange"
      >
        <el-option
          v-for="item in provinceList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="城市" prop="city" required>
      <el-select
        v-model="cityValue"
        placeholder="请选择城市"
        style="width: 100%"
      >
        <el-option
          v-for="item in cityList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { regionData, codeToText } from "element-china-area-data";

const props = defineProps<{
  province: string;
  city: string;
}>();

const emit = defineEmits<{
  (e: "update:province", value: string): void;
  (e: "update:city", value: string): void;
}>();

const provinceValue = ref(props.province);
const cityValue = ref(props.city);

// 省份列表
const provinceList = regionData;
// 城市列表
const cityList = ref<any[]>([]);

// 省份改变时，加载对应城市
const handleProvinceChange = (provinceCode: string) => {
  cityValue.value = "";
  emit("update:city", "");

  const province = regionData.find((item) => item.value === provinceCode);
  if (province && province.children) {
    cityList.value = province.children;
  } else {
    cityList.value = [];
  }
};

// 监听 province 变化
watch(
  () => props.province,
  (newVal) => {
    if (newVal !== provinceValue.value) {
      provinceValue.value = newVal;
    }
    if (newVal) {
      handleProvinceChange(newVal);
    }
  }
);

// 监听 city 变化
watch(
  () => props.city,
  (newVal) => {
    if (newVal !== cityValue.value) {
      cityValue.value = newVal;
    }
  }
);

// 监听内部值变化
watch(provinceValue, (newVal) => {
  emit("update:province", newVal);
});

watch(cityValue, (newVal) => {
  emit("update:city", newVal);
});

// 编码转名称的工具函数
const getProvinceName = (code: string) => codeToText[code] || "--";
const getCityName = (code: string) => codeToText[code] || "--";
</script>

<style scoped>
.region-select {
  display: flex;
  gap: 12px;
  align-items: center;
}

.region-select :deep(.el-select) {
  width: 120px;
}
</style>
